import { Command } from 'commander'
import chalk from 'chalk'
import { createRequire } from 'module'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'

// Import commands
import { initCommand } from './commands/init'
import { buildCommand } from './commands/build'
import { devCommand } from './commands/dev'

const require = createRequire(import.meta.url)
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// Get package.json info
const packagePath = join(__dirname, '../package.json')
const packageJson = require(packagePath)

const program = new Command()

program
  .name('my-cli')
  .description('A modern CLI tool built with TypeScript and Vite')
  .version(packageJson.version)

// Add commands
program.addCommand(initCommand)
program.addCommand(buildCommand)
program.addCommand(devCommand)

// Global error handler
program.exitOverride(err => {
  if (err.code === 'commander.version') {
    console.log(chalk.blue(`v${packageJson.version}`))
    process.exit(0)
  }
  if (err.code === 'commander.help') {
    process.exit(0)
  }
  console.error(chalk.red('Error:'), err.message)
  process.exit(1)
})

// Handle unknown commands
program.on('command:*', () => {
  console.error(
    chalk.red('Invalid command:'),
    chalk.yellow(program.args.join(' '))
  )
  console.log(chalk.gray('See --help for a list of available commands.'))
  process.exit(1)
})

// Parse arguments
program.parse()

export { program }
